#include<iostream>
#include<mysql/mysql.h>
#include<string>
using namespace std;

const string host = "127.0.0.1";
const string user_name = "spray_rain";
const string passwd = "langyu123";
const string db = "my_test";
unsigned int port = 8848;



int main()
{
    MYSQL test;
    MYSQL *my_test = mysql_init(&test);

    my_test = mysql_real_connect(my_test, host.c_str(), user_name.c_str(), passwd.c_str()
    , db.c_str(), port, nullptr, 0);
    if (my_test == nullptr) cout << "connect mysql server error" <<endl;
    else cout << "connect mysql server successful" <<endl;
    mysql_set_character_set(my_test, "utf8");

    //对数据库进行删改操作
    //string commend = "insert into student values('0915011', '暮云', 'girl', 'HeBei', 1997, 'computer')";
    //string commend = "delete from student where name = '暮云'";
    string commend = "select * from student";
    int check = mysql_query(my_test, commend.c_str());
    if (check == 0) cout << "alter table successful" <<endl;
    else cout << "alter table error" <<endl;

    MYSQL_RES * ret_select = mysql_store_result(my_test);
    if (ret_select == nullptr) cout << "select table error" <<endl;
    else cout << "select table successful" <<endl;

    //获取表格的行和列
    int row_num = mysql_num_rows(ret_select);
    int field_num = mysql_num_fields(ret_select);
    cout << "行数： "<< row_num << " 列数： "<< field_num <<endl;

    //获取表格的列名
    MYSQL_FIELD * field_property = mysql_fetch_fields(ret_select);
    for (int i = 0; i < field_num; i++)
    {
        cout << field_property[i].name << '\t' ;
    }

    cout <<endl;
    //获取表格的内容
    
    for (int i = 0; i < row_num; i++)
    {   
        MYSQL_ROW table_body = mysql_fetch_row(ret_select);
        for (int j = 0; j < field_num; j++)
        {
            cout << table_body[j] <<'\t';
        }

        cout <<endl;
    }

    return 0;
}